import React, { Component } from 'react'
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Form,
  InputNumber,
  Popconfirm,
  message,
} from 'antd'
import {
  findGoods,
  findGoodsByName,
  updateGoods,
  deleteGoods,
} from '../../../api/goods.js'
import { Link } from 'react-router-dom'
let { Option } = Select

const callBackChange = ({
  editing,
  dataIndex,
  title,
  record,
  inputType,
  select,
  index,
  children,
  ...restProps
}) => {
  const selectNode = (
    <Select>
      <Option value="123">123</Option>
    </Select>
  )
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {select ? selectNode : inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  )
}

export default class ListHome extends Component {
  state = {
    data: [],
    searchData: '',
    editingKey: '',
    form: {},
  }

  componentDidMount() {
    this.getGoods()
  }
  // 获取商品列表
  getGoods = () => {
    findGoods().then((res) => {
      this.setState({ data: res.data.data })
      // console.log(res.data.data)
    })
  }
  // 搜索
  search = (value) => {
    findGoodsByName(value).then((res) => {
      // console.log(res.data.data)
      this.setState({ searchData: res.data.data })
    })
  }
  // 删除产品
  deletePro = (v) => {
    deleteGoods({ id: v._id }).then((res) => {
      message.success(res.data.msg)
      this.getGoods()
    })
  }

  // 判断是否是修改状态
  isEditing = (record) => record._id === this.state.editingKey
  // 点击修改按钮
  edit = (v) => {
    // console.log(this.formRef)
    this.formRef.setFieldsValue({
      ...v,
    })
    this.setState({ editingKey: v._id, form: v })
  }
  // 保存修改上传
  save = (v) => {
    let obj = { ...v, id: this.state.editingKey }
    console.log(obj)
    updateGoods(obj).then((res) => {
      this.getGoods()
      this.setState({ editingKey: '' })
      message.success(res.data.msg)
    })
  }
  // 取消修改
  cancel = () => {
    this.setState({ editingKey: '' })
  }

  render() {
    let { data, searchData } = this.state
    const columns = [
      {
        title: '商品名称',
        dataIndex: 'name',
        key: 'name',
        editable: false,
      },
      {
        title: '商品描述',
        dataIndex: 'title',
        key: 'title',
        width: '20%',
        editable: false,
      },
      {
        title: '商品价格',
        dataIndex: 'price',
        key: 'price',
        editable: true,
        render: (v) => <span>￥{v}</span>,
      },
      {
        title: '商品类型',
        dataIndex: ['type', 'name'],
        key: 'type',
        editable: false,
        render: (v) => <span>{v}</span>,
      },
      {
        title: '商品状态',
        dataIndex: 'state',
        key: 'state',
        render: (values) => (
          <>
            {values ? (
              <Button type={values ? 'primary' : ''}>点击下架</Button>
            ) : (
              <Button type="default">点击上架</Button>
            )}
          </>
        ),
      },
      {
        title: '操作',
        key: 'action',
        width: '20%',
        render: (value) => {
          // console.log(record)
          const editable = this.isEditing(value)
          return editable ? (
            <span>
              <Button
                htmlType="submit"
                style={{
                  marginRight: 8,
                }}
              >
                保存
              </Button>
              <Popconfirm title="确定要取消修改?" onConfirm={this.cancel}>
                <Button>取消</Button>
              </Popconfirm>
            </span>
          ) : (
            <>
              <Button
                type="link"
                disabled={this.state.editingKey !== ''}
                onClick={() => this.edit(value)}
              >
                修改
              </Button>
              <Button type="link" onClick={() => this.deletePro(value)}>
                删除
              </Button>
              <Button type="link" href="/home/product/list/detail">
                详情
              </Button>
            </>
          )
        },
      },
    ]
    const mergedColumns = columns.map((col) => {
      if (!col.editable) {
        return col
      }

      return {
        ...col,
        onCell: (record) => {
          // console.log(record)
          return {
            record,
            inputType: col.dataIndex === 'price' ? 'number' : 'text',
            select: col.key === 'type' ? true : false,
            dataIndex: col.dataIndex,
            title: col.title,
            editing: this.isEditing(record),
          }
        },
      }
    })
    return (
      <>
        <Card
          title={
            // 搜索表格
            <Form
              name="search"
              onFinish={this.search}
              style={{ display: 'flex', height: '32px' }}
            >
              <Form.Item
                name="searchType"
                rules={[
                  {
                    // required: true,
                    message: '请输入用户名!',
                  },
                ]}
              >
                <Select style={{ width: '110px' }}>
                  <Option value="name">name</Option>
                  <Option value="title">title</Option>
                </Select>
              </Form.Item>
              &nbsp;&nbsp;&nbsp;
              <Form.Item
                name="searchData"
                rules={[
                  {
                    // required: true,
                    message: '请输入用户名!',
                  },
                ]}
              >
                <Input style={{ width: '150px' }} />
              </Form.Item>
              &nbsp;&nbsp;&nbsp;
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
              </Form.Item>
            </Form>
          }
          extra={
            // <AddCat></AddCat>
            <Link to="/home/product/list/add">添加商品</Link>
          }
          style={{ width: '100%' }}
        >
          <Form
            form={this.formRef}
            ref={(c) => (this.formRef = c)}
            name="change"
            onFinish={this.save}
          >
            <Table
              components={{
                body: {
                  cell: callBackChange,
                },
              }}
              scroll={{ y: '350px' }}
              rowKey={(v) => v._id}
              columns={mergedColumns}
              dataSource={searchData || data}
              bordered
            />
          </Form>
        </Card>
      </>
    )
  }
}
